<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/style/admin.css" media="all">
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">用户设置</div>
                <div class="layui-card-body">
                    <div style="margin-bottom: 10px;">
                        <div class="layui-input-item" style="float:left;padding-right:10px;">
                            <form class="layui-form">
                                <div class="layui-inline">
                                    <input id="search-name" type="text"
                                           placeholder="请输入姓名" class="layui-input layui-input-search">
                                </div>
                                <div class="layui-inline">
                                    <a id="btn-search" class="layui-btn">查找</a>
                                </div>
                            </form>
                        </div>
                        <div style="float:right;">
                            <a id="btn-add" class="layui-btn">添加</a>
                            <a id="btn-refresh" class="layui-btn layui-btn-primary">刷新</a>
                        </div>
                        <div style="clear:both;"></div>
                    </div>
                    <table class="layui-hide" id="user-table" lay-filter="user-table"></table>
                    <script type="text/html" id="toolbar-operation">
                        <a class="layui-btn layui-btn-xs" lay-event="edit">详情</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="reset">重置密码</a>
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="user-form">
    <div class="layui-card">
        <div class="layui-card-header">用户详情</div>
        <div class="layui-card-body">
            <form class="layui-form" action="#" lay-filter="user-form">
                <input type="hidden" name="id">
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">账号</label>
                    <div class="layui-input-block">
                        <input type="text" name="account" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="role" lay-skin="primary" th:each="item:${roles}"
                               th:value="${item.id}" th:title="${item.name}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="form-submit">确定
                    </button>
                </div>
            </form>
        </div>
    </div>
</script>
<script type="text/html" id="stateTpl">
    <input type="checkbox" name="state" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="changeState"
           {{ d.isEnabled== 1 ? 'checked' : '' }}>
</script>
<script src="/layui/layui.js"></script>
<script th:inline="none">
    layui.config({
        base: '/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table', 'form'], function () {
        var $ = layui.$;
        var table = layui.table;
        var form = layui.form;
        var admin = layui.admin;
        var popupIndex;
        var userId;

        table.render({
            elem: '#user-table',
            url: 'users',
            title: '',
            skin: 'line',
            cols: [[
                {field: 'name', title: '姓名'},
                {field: 'account', title: '账号'},
                {field: 'roleNames', title: '角色'},
                {field: 'isEnabled', title: '状态', width: 150, templet: '#stateTpl'},
                {fixed: 'right', title: '操作', width: 250, align: 'center', toolbar: '#toolbar-operation'}
            ]],
            page: true
        });

        function showUserForm() {
            popupIndex = admin.popupRight({
                area: '360px',
                success: function () {
                    var formHtml = $('#user-form').html();
                    $('#' + this.id).html(formHtml);
                    form.render();
                }
            });
            return popupIndex;
        }

        function closePopupForm() {
            if (popupIndex) {
                layer.close(popupIndex);
            }
        }

        function search() {
            table.reload('user-table', {
                where: {
                    name: $('#search-name').val(),
                }
            });
        }

        function resetPassword(userId) {
            layer.confirm('真的重置密码吗？', function (index) {
                var url = 'users/' + userId + '/reset-password';
                $.get(url, function (result) {
                    if (result.code == 0) {
                        layer.msg('密码重置成功');
                    } else {
                        layer.msg('密码重置失败');
                    }
                });
                layer.close(index);
            });
        }

        $("#btn-search").on('click', function () {
            search();
        })

        $('#keyword').keypress(function (e) {
            if (e.which == 13) {
                search();
            }
        });

        $("#btn-add").on('click', function () {
            popupIndex = showUserForm();
        })

        $("#btn-refresh").on('click', function () {
            table.reload('user-table');
            layer.msg('表格已刷新');
        })

        table.on('tool(user-table)', function (obj) {
            var data = obj.data;
            userId = data.id;
            if (obj.event === 'del') {
                layer.confirm('真的删除该记录吗？', function (index) {
                    $.ajax({
                        url: 'users/' + data.id,
                        type: 'DELETE',
                        success: function (result) {
                            if (result.code == 0) {
                                layer.msg('删除成功');
                                table.reload('user-table');
                            } else {
                                layer.msg('删除失败');
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                showUserForm();
                form.val('user-form', data);
                var roles = data.roles;
                if (roles) {
                    var ids = roles.split(',');
                    for (var i in ids) {
                        $('input[name="role"][value="' + ids[i] + '"]').prop("checked", true);
                    }
                    form.render();
                }
            } else if (obj.event = 'reset') {
                console.log("data.id:" + data.id);
                resetPassword(data.id);
            }
        });

        form.on('submit(form-submit)', function (data) {
            var postData = data.field;
            var ids = [];
            var roles = "";
            $('input[name="role"]:checked').each(function (index, item) {
                ids.push($(this).val());
            });
            for (var i in ids) {
                roles += ids[i] + ",";
            }
            if (roles.length > 0) {
                roles = roles.substring(0, roles.length - 1)
            }
            postData.roles = roles;
            $.ajax({
                url: 'users',
                type: 'PUT',
                data: postData,
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg('提交成功');
                        table.reload('user-table');
                    } else {
                        layer.msg('提交失败');
                        console.error('提交失败');
                    }
                }
            });
            closePopupForm();
            return false;
        });

        form.on('switch(changeState)', function (obj) {
            $.get('users/' + obj.value + '/toggle-state', function (result) {
                if (result.code != 0) {
                    layer.msg('修改状态失败');
                }
            });
        });

    });
</script>
</body>
</html>